package com.jnshu.tools.binding;

import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;

@Slf4j
public class EmailUtil {
    private static final String url = "http://api.sendcloud.net/apiv2/mail/send";
    private static final String apiUser = "xuhaipeng_test_Lvn4xt";
    private static final String apiKey = "yhfzYw9wwUmRnVL7";
    private static final String from = "sendcloud@sendcloud.org";
    private static final String fromName = "DayDayUp";
    private static final String subject = "来自DayDayUp的邮件";

    /**邮件内容组装*/
    private static String emailContent(String code){
        log.info("获取的code："+code);
        String sendBodyStart = "您的验证码是：";
        String sendBodyEnd = ",您正在进行身份验证，打死也不能告诉别人";
        return sendBodyStart+code+sendBodyEnd;
    }

    /**发送普通邮件*/
    public static Boolean sendEmail(String recipient,String code)throws IOException {
        log.info("邮箱地址："+recipient);
        log.info("验证码："+code);
        log.info("发件处："+from);
        log.info("发件人："+fromName);
        log.info("邮件标题："+subject);

        //把组装的邮件内容赋值给字符串变量html
        String html = emailContent(code);
        log.info("验证内容："+html);

        //创建客户端对象和post对象
        HttpPost httPost = new HttpPost(url);
        CloseableHttpClient httpClient = HttpClients.createDefault();

        //设置参数集合
        List<NameValuePair> params = new ArrayList<>();
        params.add(new BasicNameValuePair("apiUser",apiUser));
        params.add(new BasicNameValuePair("apiKey",apiKey));
        params.add(new BasicNameValuePair("to",recipient));
        params.add(new BasicNameValuePair("from",from));
        params.add(new BasicNameValuePair("fromName",fromName));
        params.add(new BasicNameValuePair("subject",subject));
        params.add(new BasicNameValuePair("html",html));
        //post方法提交
        httPost.setEntity(new UrlEncodedFormEntity(params,"UTF-8"));
        //响应
        HttpResponse response = httpClient.execute(httPost);
        //处理响应
        if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
            //读取xml文档，解析返回数据
            String result = EntityUtils.toString(response.getEntity());
            log.info("邮件发送结果："+result);
            return true;
        }else {
            log.info("邮件发送失败");
            httPost.releaseConnection();
            return false;
        }
    }

    /**发送附件邮件*/
    public static void sendEmailAttachment(String recipient,String code)throws IOException{

        String html = emailContent(code);

        //创建客户端对象和post对象
        HttpPost httpPost = new HttpPost(url);
        CloseableHttpClient httpClient = HttpClients.createDefault();

        //涉及到附件上传则需要使用MultipartEntityBuilder
        MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create();
        //浏览器兼容
        entityBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
        //设置字符集
        entityBuilder.setCharset(Charset.forName("UTF-8"));

        //文本类型设置
        ContentType TEXT_PLAIN = ContentType.create("text/plain",Charset.forName("UTF-8"));
        entityBuilder.addTextBody("apiUser",apiUser,TEXT_PLAIN);
        entityBuilder.addTextBody("apiKey",apiKey,TEXT_PLAIN);
        entityBuilder.addTextBody("to",recipient,TEXT_PLAIN);
        entityBuilder.addTextBody("from",from,TEXT_PLAIN);
        entityBuilder.addTextBody("fromName",fromName, TEXT_PLAIN);
        entityBuilder.addTextBody("subject",subject,TEXT_PLAIN);
        entityBuilder.addTextBody("html",html,TEXT_PLAIN);

        //添加附件
        ContentType OCTEC_STREAM = ContentType.create("application/octet-stream",Charset.forName("UTF-8"));

        //单附件
        File file = new File("E:\\测试.txt");
        String attachName = "测试.txt";
        entityBuilder.addBinaryBody("attachment",file,OCTEC_STREAM,attachName);

        //多附件
        File file2 = new File("E:\\测试2.txt");
        String attachName2 = "测试2.txt";
        entityBuilder.addBinaryBody("attachment",file2,OCTEC_STREAM,attachName2);

        //post方法提交
        httpPost.setEntity(entityBuilder.build());

        HttpResponse response = httpClient.execute(httpPost);
        //处理响应
        if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
            //读取xml文档，解析返回数据
            String result = EntityUtils.toString(response.getEntity());
            System.out.println(result);
        }else {
            System.out.println("Error");
        }
        httpPost.releaseConnection();
    }
}
